package threadTest.myCompletableFuture;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 功能描述: 线程编排, 先执行任务A ,任务A结束后再执行任务B,然后执行 任务C
 * 2024/08/09
 *
 * 	then*
 * @author ZhangYi
 */
public class CompletableFutureThenExecutor {

	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, Runtime.getRuntime().availableProcessors(),
				0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());

		CompletableFuture<String> userInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
			return new UserService().getUserInfo();
		}, executor);

		Function<String,String> taskB = s ->{
			// 此时的s 是上一个 CompletableFuture 的执行结果
			return "查询用户信息完毕,校验用户token"+s;
		};

		Function<String,String> taskC = s ->{
			// 此时的s 是上一个 CompletableFuture 的执行结果
			return "校验用户token完毕,获取用户角色信息"+s;
		};

		// 按序执行流程, A -> B -> C -> D
		userInfoCompletableFuture
				.thenApply(taskB)
				.thenApply(taskC)
				.thenAccept(res ->{
					System.out.println(res);
				});

		userInfoCompletableFuture.thenRun(
				()->{
					System.out.println("runnable 接口不接受返回值,也不接受输入值, 任务执行完毕");
				}
		);



		executor.shutdown();
		try {
			if (!executor.awaitTermination(5, TimeUnit.SECONDS)){
				executor.shutdownNow();
				if (!executor.awaitTermination(5, TimeUnit.SECONDS)){
					System.out.println("线程池关闭失败");
				}
			}
		} catch (InterruptedException e) {
			executor.shutdownNow();
		}

	}
}
